/**
 * @description 收货地址路由
 * @author 李哲
 */
const router = require('koa-router')()
const { errnoModel, successModel } = require('../res-model/index');
const loginCheng = require('../middleware/loginCheck');
const { setAddress, getAddressList, getAddressOne, updateAddress } = require('../controller/address');

router.prefix('/api/user')

//创建收货地址
router.post('/address', loginCheng, async (ctx, next) => {
    const { username } = ctx.session.userInfor;
    const data = ctx.request.body;
    try {
        const newAddress = await setAddress(username, data);
        ctx.body = new successModel(newAddress);
    } catch (err) {
        console.error(err);
        ctx.body = new errnoModel(1004, '创建收货地址失败')
    }
})
//获取收货地址列表
router.get('/address', loginCheng, async (ctx, next) => {
    const { username } = ctx.session.userInfor;
    const newAddress = await getAddressList(username)
    ctx.body = new successModel(newAddress);
})
//获取单个收货地址
router.get('/address/:id', loginCheng, async (ctx, next) => {
    const id = ctx.params.id;
    const newAddress = await getAddressOne(id);
    ctx.body = new successModel(newAddress);
})
//更新收货地址信息
router.post('/updateAddress/:id', loginCheng, async (ctx, next) => {
    const id = ctx.params.id;
    const { username } = ctx.session.userInfor
    const data = ctx.request.body
    try {
        const newAddress = await updateAddress(id, username, data)
        ctx.body = new successModel(newAddress)
    } catch (err) {
        console.error(err);
        ctx.body = new errnoModel(1005, '修改地址信息失败');
    }
})
module.exports = router;